package com.tekj.cxqcb.view.Module.activity;

import android.graphics.drawable.BitmapDrawable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tekj.cxqcb.MainBActivity;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.config.Urls;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.GetCarBrandAndModelBean;
import com.tekj.cxqcb.operation.resultBean.GetCarListBean;
import com.tekj.cxqcb.view.Module.adapter.BrandScreenAdapter;
import com.tekj.cxqcb.view.Module.adapter.Screen2Adapter;
import com.tekj.cxqcb.view.Module.adapter.Screen3Adapter;
import com.tekj.cxqcb.view.Module.adapter.ScreenGoodsadapter;
import com.tekj.cxqcb.view.Module.bean.ScreenBean;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import common.base.MainApplication;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.plugins.tbs.WebCoreAction;
import common.tool.pinying.PinyinComparatorBrand;
import common.tool.pinying.PinyinUtils;
import common.tool.pinying.TitleItemDecorationBrand;
import common.widget.WaveSideBar;

/**
 * 卖车推荐
 */
public class BuyingRecommendationActivity extends BaseActivity {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.img_clear)
    ImageView imgClear;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tv_tab1)
    TextView tvTab1;
    @BindView(R.id.tv_tab2)
    TextView tvTab2;
    @BindView(R.id.tv_tab3)
    TextView tvTab3;
    @BindView(R.id.tv_tab4)
    TextView tvTab4;
    @BindView(R.id.ll_tab)
    LinearLayout llTab;
    @BindView(R.id.tv_line)
    TextView tvLine;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.rv_main)
    RecyclerView rvMain;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinator;


    private String names[] = {"销量最低", "售价最低", "月供最低", "销量最高", "售价最高"};
    private String ids[] = {"sales_volume", "platformPrice", "platformPrice", "sales_volume", "platformPrice"};
    private String sortingRules[] = {"", "", "", "desc", "desc"};

    private List<ScreenBean> list;
    private Screen3Adapter screen3Adapter;

    private List<GetCarBrandAndModelBean.DataBean.BrandListBean> list2;
    private BrandScreenAdapter screenAdapter;

    private List<GetCarBrandAndModelBean.DataBean.ModelListBean> list3;
    private Screen2Adapter screen2Adapter;

    private ScreenGoodsadapter goodsadapter;
    private BusinessDao businessDao;
    private int p = 1;
    private String query;

    @Override
    public void init() {
        tvTitle.setText("卖车推荐");
        businessDao = new BusinessDao(this, this);
        list = new ArrayList<>();
        for (int i = 0; i < names.length; i++) {
            list.add(new ScreenBean(names[i], ids[i], sortingRules[i]));
        }
        businessDao.GetCarBrandAndModel();
//        screenGoodsadapter=new ScreenGoodsadapter()

        //搜索
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 0) {
                    tvSearch.setVisibility(View.VISIBLE);
                } else {
                    tvSearch.setVisibility(View.INVISIBLE);
                    query = "";
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    @Override
    public int setLayout() {
        return R.layout.activity_buying_recommendation;
    }

    @Override
    public void initLoadStart() {

    }

    @Override
    public void initLoadEnd() {

    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 获取所有分类:
                GetCarBrandAndModelBean modelBean = (GetCarBrandAndModelBean) bindingViewBean.getBean();
                if ("0000000".equals(modelBean.getCode())) {
                    initFilter(modelBean.getData());
                }
                break;
            case 筛选后的车型:
                GetCarListBean listBean = (GetCarListBean) bindingViewBean.getBean();
                if ("0000000".equals(listBean.getCode())) {
                    if (p == 1) {
                        goodsadapter.setNewData(listBean.getData().getList());
                    } else {
                        goodsadapter.addData(listBean.getData().getList());
                    }
                    goodsadapter.loadMoreComplete();
                    if (listBean.getData().getList().size() < 10) {
                        goodsadapter.loadMoreEnd();
                    }
                }
                break;
        }
    }


    @OnClick({R.id.ll_back, R.id.tv_search, R.id.tv_tab1, R.id.tv_tab2, R.id.tv_tab3, R.id.tv_tab4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_search:
                break;
            case R.id.tv_tab1:
                showPop(screen3Adapter, false);
                break;
            case R.id.tv_tab2:
                showPop(screenAdapter, true);
                break;
            case R.id.tv_tab3:
                showPop(screen2Adapter, false);
                break;
            case R.id.tv_tab4:
                showPop(new Screen3Adapter(null), false);
                break;
        }
    }


    /**
     * 获取数据
     */
    public void getData() {
        String orderBy = "";
        String name = "";
        String brandIds = "";
        String modelIds = "";
        String d = "";
        if (screen3Adapter != null && screen3Adapter.getCheckItemPosition() != -1) {
            orderBy = list.get(screen3Adapter.getCheckItemPosition()).getId();
            d = list.get(screen3Adapter.getCheckItemPosition()).getSortingRules();
        }

        if (screenAdapter != null && screenAdapter.getCheckItemPosition() != -1) {
            brandIds = list2.get(screenAdapter.getCheckItemPosition()).getId();
        }

        if (screen2Adapter != null && screen2Adapter.getCheckItemPosition() != -1) {
            modelIds = list3.get(screen2Adapter.getCheckItemPosition()).getId();
        }

        businessDao.GetCarList(orderBy, p, name, brandIds, modelIds, d);

    }

    /**
     * 设置筛选adapter
     *
     * @param bean
     */
    public void initFilter(final GetCarBrandAndModelBean.DataBean bean) {

        //品牌
//        list2 = bean.getBrandList();
        list2 = filledData(bean.getBrandList());
        screenAdapter = new BrandScreenAdapter(activity, list2, activity);
        screenAdapter.setOnItemClickListener(new BrandScreenAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                screenAdapter.setCheckItem(screenAdapter.getCheckItemPosition() == position ? -1 : position);
                p = 1;
                getData();
                popupWindow.dismiss();
            }
        });
        mComparator = new PinyinComparatorBrand();
        Collections.sort(list2, mComparator);

        mDecoration = new TitleItemDecorationBrand(activity, list2);

        //车型
        list3 = bean.getModelList();
        screen2Adapter = new Screen2Adapter(list3);
        screen2Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                screen2Adapter.setCheckItem(screen2Adapter.getCheckItemPosition() == position ? -1 : position);
                p = 1;
                getData();
                popupWindow.dismiss();
            }
        });

        //排序
        screen3Adapter = new Screen3Adapter(list);
        screen3Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                screen3Adapter.setCheckItem(screen3Adapter.getCheckItemPosition() == position ? -1 : position);
                p = 1;
                getData();
                popupWindow.dismiss();
            }
        });


        goodsadapter = new ScreenGoodsadapter(null);

        rvMain.setLayoutManager(new LinearLayoutManager(activity));
        rvMain.setAdapter(goodsadapter);
        rvMain.addItemDecoration(new SpacesItemDecoration(1));
        goodsadapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                p++;
                getData();
            }
        }, rvMain);

        goodsadapter.setEmptyView(R.layout.rv_empty);
        goodsadapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                new WebCoreAction(activity,
                        Urls.Domain_H5 + "sale-car-detail/"
                                + goodsadapter.getData().get(position).getId()
                                + MainBActivity.getUserID()
                                + "&token=" + MainApplication.UserToken);
            }
        });
        getData();
    }


    public List<GetCarBrandAndModelBean.DataBean.BrandListBean> filledData(List<GetCarBrandAndModelBean.DataBean.BrandListBean> date) {

        for (int i = 0; i < date.size(); i++) {
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(date.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                date.get(i).setLetters(sortString.toUpperCase());
            } else {
                date.get(i).setLetters("#");
            }
        }
        return date;

    }

    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;

    private LinearLayoutManager manager;
    private PinyinComparatorBrand mComparator;
    private TitleItemDecorationBrand mDecoration;

    private void showPop(RecyclerView.Adapter adapter, boolean isbar) {
        popupView = View.inflate(activity, R.layout.pop_screen, null);
        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);


        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, -1, Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);


        RecyclerView rvScreen = popupView.findViewById(R.id.rv_screen);
        rvScreen.setLayoutManager(new LinearLayoutManager(activity));
        rvScreen.setHasFixedSize(true);
        rvScreen.setAdapter(adapter);
        if (isbar) {
            manager = new LinearLayoutManager(activity);
//            manager.setOrientation(LinearLayoutManager.VERTICAL);
            WaveSideBar sideBar = popupView.findViewById(R.id.sideBar);
            sideBar.setVisibility(View.VISIBLE);
            sideBar.setOnTouchLetterChangeListener(new WaveSideBar.OnTouchLetterChangeListener() {
                @Override
                public void onLetterChange(String letter) {
                    //该字母首次出现的位置
                    int position = screenAdapter.getPositionForSection(letter.charAt(0));
                    if (position != -1) {
                        manager.scrollToPositionWithOffset(position, 0);
                    }
                }
            });

            rvScreen.setLayoutManager(manager);
            rvScreen.addItemDecoration(mDecoration);
            rvScreen.addItemDecoration(new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL));

        }


        popupWindow.showAsDropDown(tvLine/*, Gravity.RIGHT, 0, 0*/);
        popupView.startAnimation(animation);

    }
}
